﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;

using System.Data;
using System.Data.Objects;

namespace RL
{
    /// <summary>
    /// Логика взаимодействия для ucFullRouteInfo.xaml
    /// </summary>
    public partial class ucFullRouteInfo : UserControl
    {
        private routelistEntities db;
        private RouteTable rt;
        private RoutePlan rplan;
        IEditableCollectionView vwInfo;
        IEditableCollectionView vwSchedule;


        public routelistEntities ContextDB { 
            get 
            { 
                return db;
            } 
            set 
            {
                db = value;
            } 
        }
        public RouteTable RouteTableValue { 
            get 
            { 
                return rt; 
            } set 
            { 
                rt = value;
                RefreshData();
            } 
        }

        IEnumerable<RouteDepartureSchedule> GetRouteDepartureScheduleLinq(routelistEntities db, RouteTable rt)
        {
            return from o in db.RouteDepartureSchedule orderby o.time_departure.Trim() + o.time_arrive.Trim() where o.id_routetable == rt.id select o;
        }

        ObjectQuery<RouteDepartureSchedule> GetRouteDepartureSchedule(routelistEntities routelistEntities, RouteTable rt)
        {
            string queryString = "SELECT VALUE RouteDepartureSchedule FROM routelistEntities.RouteDepartureSchedule as RouteDepartureSchedule WHERE RouteDepartureSchedule.id_routetable=@prm ORDER BY Trim(RouteDepartureSchedule.time_departure)+Trim(RouteDepartureSchedule.time_arrive)";
            
            ObjectQuery<RouteDepartureSchedule> query = new ObjectQuery<RouteDepartureSchedule>(queryString, routelistEntities);
            query.Include("RouteTable");
            query.Parameters.Add(new ObjectParameter("prm", rt.id));
            return query;
        }

        /// <summary>
        /// Номер выхода
        /// </summary>
        public int InternalRouteNumber { get; set; }
        public ucFullRouteInfo()
        {
            InitializeComponent();
            if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
            {
                db = new routelistEntities(Properties.Settings.Default.DebugConnection);
            }
            else
            {
               // db = new routelistEntities();
            }
        }

        /// <summary>
        /// Обновить данные формы
        /// </summary>
        public void RefreshData()
        {
            if (null == db)
            {
                return;
            }
            if (null == rt)
            {
                return;
            }
            ucRouteInfo1.route_table = rt;
            CollectionViewSource cvs_info = (CollectionViewSource)FindResource("sourceInfo");
            cvs_info.Source = from o in db.RouteDepartureCharact.Include("Routes") orderby o.Routes.number where o.id_routetable == rt.id select o;
            vwInfo = (IEditableCollectionView)cvs_info.View;
            CollectionViewSource cvs_schedule = (CollectionViewSource)FindResource("sourceSchedule");

            //ObjectQuery<RouteDepartureSchedule> qr = GetRouteDepartureSchedule(db, rt);
            //cvs_schedule.Source = qr.Execute(MergeOption.AppendOnly);
            //cvs_schedule.Source = from o in db.RouteDepartureSchedule orderby o.time_departure.Trim()+o.time_arrive.Trim()  where o.id_routetable == rt.id select o;
            cvs_schedule.Source = GetRouteDepartureScheduleLinq(db, rt);

            vwSchedule = (IEditableCollectionView)cvs_schedule.View;
            CollectionViewSource cvs_routes = (CollectionViewSource)FindResource("sourceRoutes");
            cvs_routes.Source = from o in db.Routes orderby o.name where o.del == false select o;

            rplan = (from o in rt.RoutePlan select o).FirstOrDefault();
            if (null == rplan)
            {
                rplan = new RoutePlan();
                rplan.monday = 0;
                rplan.tuesday = 0;
                rplan.wednesday = 0;
                rplan.thursday = 0;
                rplan.friday = 0;
                rplan.saturday = 0;
                rplan.sunday = 0;
                rt.RoutePlan.Add(rplan);
            }
            gridplandays.DataContext = rplan;
        }

        /// <summary>
        /// СохранитьДанныеФормы
        /// </summary>
        public void SaveData()
        {
            if (null == db)
            {
                MessageBox.Show("Данные не сохранены");
                return;
            }
            try
            {
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void buttonAddSchedule_Click(object sender, RoutedEventArgs e)
        {
            if (null == vwSchedule) return;
            if (null == rt) return;
            RouteDepartureSchedule item = (RouteDepartureSchedule)vwSchedule.AddNew();
            Routes itemRoute = (from o in db.Routes orderby o.number select o).FirstOrDefault();
            item.id_route = itemRoute.id;
            item.id_routetable = rt.id;
            item.name_busstop = "";
            item.time_arrive = "";
            item.time_departure = "";
            try
            {
                vwSchedule.CommitNew();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            SaveData();
            listViewSchedule.ScrollIntoView(item);
            listViewSchedule.SelectedItem = item;
        }

        private void buttonDeleteSchedule_Click(object sender, RoutedEventArgs e)
        {
            if (null == vwSchedule) return;
            if (null == rt) return;
            RouteDepartureSchedule item = listViewSchedule.SelectedItem as RouteDepartureSchedule;
            if (null == item) return;
            db.DeleteObject(item);
            //item.del = !item.del;
            SaveData();
            RefreshData();
        }

        private void buttonEditSchedule_Click(object sender, RoutedEventArgs e)
        {

        }

        private void buttonAddInfo_Click(object sender, RoutedEventArgs e)
        {
            if (null == db) return;
            if (null == rt) return;
            RouteDepartureCharact item = (RouteDepartureCharact)vwInfo.AddNew();
            Routes itemRoute = (from o in db.Routes orderby o.number select o).FirstOrDefault();
            item.id_routetable = rt.id;
            item.id_route = itemRoute.id;
            item.column_2 = 0;
            
            item.length = 0;
            item.free_length = 0;
            item.reis = 0;
            item.work_time = 0;
            item.rest_time = 0;
            try
            {
                vwInfo.CommitNew();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            SaveData();
            listViewInfo.ScrollIntoView(item);
            listViewInfo.SelectedItem = item;
        }

        private void buttonDeleteInfo_Click(object sender, RoutedEventArgs e)
        {
            if (null == db) return;
            if (null == rt) return;
            RouteDepartureCharact item = listViewInfo.SelectedItem as RouteDepartureCharact;
            if (null == item) return;
            db.DeleteObject(item);
            //item.del = !item.del;
            SaveData();
            RefreshData();
        }

        private void buttonEditInfo_Click(object sender, RoutedEventArgs e)
        {

        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            RefreshData();
        }

    }
}
